package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentF extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    //界面元素;
    private TextView edit_startDate, edit_endDate, edit_orderNo, edit_styleNo;
    private Button btn_find;
    ListView myListView;
    //全局变量
    private ProgressDialog waitDialog = null;
    //全局变量
    String curLoginUserNo,curLoginUser,curServiceUrl="",curDepartNo="",curDepart="",curProduceMasterID="",
            curStyleID="",curOrderNo ="", curStyleNo ="",curStyleSort="",curFactory="";//操作员所属部门等信息;
    int curPlaceCount,curOperateTime;
    String CPUID;
    JSONArray detailJSON;
    public static final int msgFocusBarcode = 1001;
    public static final int msgError = 1002;
    public static final int msgScanOver = 1003;
    public static final int msgDetailOver = 1004;
    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public FragmentF() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建对话框，
        waitDialog=new ProgressDialog(getContext());
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerF(new MainActivity.OnTransParamsListenerF() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d("FragmentF","LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            curFactory=mParams.get("Factory").toString();
                            curPlaceCount=(Integer) mParams.get("PlaceCount");
                            curOperateTime=(Integer) mParams.get("OperateTime");
                            CPUID=mParams.get("CPUID").toString();
                            System.out.println(mParams);
                            Log.d("FragmentF","LoginParam------------------>2");
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }



    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (waitDialog.equals(null)==false) waitDialog.hide();
            if(msg!=null){
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case msgFocusBarcode:
                        //设置焦点
                        System.out.println("FragmentF 设置焦点-------------------------------1.Start");

                        System.out.println("FragmentF 设置焦点-------------------------------1.End");
                        break;
                    case msgDetailOver:
                        //显示到orderListGrid中;
                        final MyListAdapter myListAdapter=new MyListAdapter(getContext());
                        myListView.setAdapter(myListAdapter);
                        break;
                    case msgError:
                        Bundle bundle=msg.getData();
                        curToast.setText(bundle.getString("HintInfo"));
                        curToast.show();
                        break;
                    default:
                        break;
                }
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_f, container, false);
        InitView(root);
        System.out.println("fragment_f_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        //按键;
        btn_find = (Button) view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        //文本框
        edit_startDate = (EditText) view.findViewById(R.id.edit_startDate);
        edit_startDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,getString(R.string.Finish),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edit_startDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,getString(R.string.Cancel),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle(getString(R.string.PleaseSelectQueryDate));
                mDialog.show();

            }
        });
        edit_startDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_startDate","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        edit_endDate = (EditText) view.findViewById(R.id.edit_endDate);
        edit_endDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,getString(R.string.Finish),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edit_endDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,getString(R.string.Cancel),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle(getString(R.string.PleaseSelectQueryDate));
                mDialog.show();
            }
        });
        edit_orderNo = (EditText) view.findViewById(R.id.edit_orderNo);
        edit_orderNo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_orderNo","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        edit_orderNo.setOnKeyListener(new EditText.OnKeyListener(){
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode==66)
                {
                    hideIM(getView());
                    btn_find.setFocusable(true);
                    btn_find.setFocusableInTouchMode(true);
                    btn_find.requestFocus();
                    btn_find.requestFocusFromTouch();
                }
                return false;
            }
        });

        edit_styleNo = (EditText) view.findViewById(R.id.edit_styleNo);
        edit_styleNo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        edit_styleNo.setOnKeyListener(new EditText.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode==66)
                {
                    hideIM(getView());
                    btn_find.setFocusable(true);
                    btn_find.setFocusableInTouchMode(true);
                    btn_find.requestFocus();
                    btn_find.requestFocusFromTouch();
                }
                return false;
            }
        });
        //表格;
        myListView = (ListView) view.findViewById(R.id.myListView);
        myListView.setOnItemClickListener(this);
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        String StartDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime() -7 * 24 * 60 * 60 * 1000));
        String EndDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        edit_startDate.setText(StartDateStr);
        edit_endDate.setText(EndDateStr);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        hideBottomUIMenu();
        switch (v.getId()){
            case R.id.btn_find:
                //查询订单;
                refreshDetailList(curDepartNo,edit_startDate.getText().toString(),edit_endDate.getText().toString(),edit_orderNo.getText().toString(),edit_styleNo.getText().toString());
                break;
            default:
                break;
        }
    }
    //刷新工序列表;
    private void refreshDetailList(String departParam,String startDateParam,String endDateParam,String orderParam,String styleParam)
    {
        curStyleNo="";
        curOrderNo="";
        curStyleSort="";
        try {
            detailJSON=new JSONArray("[]");
            //显示到orderListGrid中;
            final MyListAdapter myListAdapter=new MyListAdapter(getContext());
            myListView.setAdapter(myListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        waitDialog.setMessage(getString(R.string.WaitingFromNetGetData));
        //执行SQL过程
        String SqlComm="Exec ScenePAD_GetEmpDetail @DepartNo='" + departParam + "',@StartDate='"+startDateParam+"',@EndDate='"+endDateParam+"',@OrderNo='"+orderParam+"',@StyleNo='"+styleParam+"',@UserNo='"+curLoginUserNo+"',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    private void ReadSQLData(String sql) {
        System.out.print("----存储过程:" + sql);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    /**
                     * [{"RoleName":"管理员"},{"RoleName":"调度"},{"RoleName":"装框操作"},{"RoleName":"物流运转"},{"RoleName":"试装箱"}]
                     */
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(sql);
                    if (jsonArray!=null&&jsonArray.length()>0){
                        String operType="";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true) {
                            operType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        }
                        if (jsonArray.optJSONObject(0).has("OperType")==true) {
                            operType=jsonArray.optJSONObject(0).getString("OperType");
                        }
                        if (operType.toUpperCase().equals("DETAIL"))
                        {
                            detailJSON=jsonArray;
                            Message msg = new Message();
                            msg.what = msgDetailOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle=new Bundle();
                            bundle.putString("HintInfo",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = msgError;
                            errmsg.setData(bundle);
                            fragmentHandler.removeMessages(errmsg.what);
                            fragmentHandler.sendMessage(errmsg);
                        }
                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle=new Bundle();
                        bundle.putString("HintInfo","未返回任何数据!");
                        errmsg.what = msgError;
                        errmsg.setData(bundle);
                        fragmentHandler.removeMessages(errmsg.what);
                        fragmentHandler.sendMessage(errmsg);
                    };

                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = msgError;
                    errmsg.setData(bundle);
                    fragmentHandler.removeMessages(errmsg.what);
                    fragmentHandler.sendMessage(errmsg);
                }
            }
        };
        new Thread(run).start();
    }



    //订单表格适配器;
    public final class MyListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public MyListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_f_listhead, null, false);
            int orderListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)orderListWidth,(int)(40)));
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                TextView tv = (TextView) convertView.findViewById(R.id.text_WorkDate);// 显示文字
                if (detailJSON.optJSONObject(position).has("WorkDate")==true) tv.setText(detailJSON.optJSONObject(position).get("WorkDate").toString());
                tv = (TextView) convertView.findViewById(R.id.text_EmpNo);// 显示文字
                if (detailJSON.optJSONObject(position).has("EmpNo")==true) tv.setText(detailJSON.optJSONObject(position).get("EmpNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_EmpName);// 显示文字
                if (detailJSON.optJSONObject(position).has("EmpName")==true) tv.setText(detailJSON.optJSONObject(position).get("EmpName").toString());
                tv = (TextView) convertView.findViewById(R.id.text_OrderNo);// 显示文字
                if (detailJSON.optJSONObject(position).has("OrderNo")==true) tv.setText(detailJSON.optJSONObject(position).get("OrderNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_StyleNo);// 显示文字
                if (detailJSON.optJSONObject(position).has("StyleNo")==true) tv.setText(detailJSON.optJSONObject(position).get("StyleNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_WorkNo);// 显示文字
                if (detailJSON.optJSONObject(position).has("WorkNo")==true) tv.setText(detailJSON.optJSONObject(position).get("WorkNo").toString());
                tv = (TextView) convertView.findViewById(R.id.text_WorkName);// 显示文字
                if (detailJSON.optJSONObject(position).has("WorkName")==true) tv.setText(detailJSON.optJSONObject(position).get("WorkName").toString());
                tv = (TextView) convertView.findViewById(R.id.text_SamValue);// 显示文字
                if (detailJSON.optJSONObject(position).has("SamValue")==true) tv.setText(detailJSON.optJSONObject(position).get("SamValue").toString());
                tv = (TextView) convertView.findViewById(R.id.text_TotalNum);// 显示文字
                if (detailJSON.optJSONObject(position).has("TotalNum")==true) tv.setText(detailJSON.optJSONObject(position).get("TotalNum").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d("msg","myListAdapter_position:"+position);
            return convertView;
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println("FragmentF 设置焦点-------------------------------1.Start");

        System.out.println("FragmentF 设置焦点-------------------------------1.End");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}
